// import {
//   lockApi
// } from "../../../api/bleLock/index.js"

const {
  bleLockHelper
} = require("./bleLockHelper.js")
class BleHelper {
  constructor() {
    this.deviceId = ""
    this.bleAvaliable = false
    this.bleDevices = []
    this.inConnect = false
    this.searchListener = null
    this.bleAdapterStateListener = null
    this.connectStateListener = null
  }

  /**
   * 打开蓝牙，不搜索
   */
  openBleAdapter(successCallback, failCallback) {
    var that = this
    this.bleDevices = []
    this.bleAdapterStateListener = res => {
      console.log("ble adapterStateChange", res)

      if (!res.available) {
        failCallback("蓝牙未打开，请打开蓝牙")
        //初始化回调
        if (bleLockHelper.initFailCallback) {
          bleLockHelper.initFailCallback()
        }
      } else if (!that.bleAvaliable) {
        that._openAdapter(successCallback, failCallback)
      }
      that.bleAvaliable = res.available
    }

    wx.onBluetoothAdapterStateChange(that.bleAdapterStateListener)
    that._openAdapter(successCallback, failCallback)
  }

  _openAdapter(successCallback, failCallback) {
    var that = this
    wx.openBluetoothAdapter({
      success: successCallback,
      fail: res => {
        console.log("ble 打开蓝牙适配器失败", res)
        if (res.errCode === 10001) {
          failCallback("请打开手机蓝牙")
        } else {
          failCallback("蓝牙打开失败")
        }
      }
    })
  }

  /**
   * 打开蓝牙，搜索蓝牙
   */
  searchBle(successCallback, failCallback) {
    var that = this
    if (this.searchListener) {
      wx.offBluetoothDeviceFound(this.searchListener)
    }
    this.openBleAdapter(res => {
      that.searchListener = (res) => {
        var selectedDevice = that._selectDevice(res.devices)
        if (selectedDevice) {
          //正确找到蓝牙门锁
          successCallback(selectedDevice)
        }
      }
      wx.onBluetoothDeviceFound(that.searchListener)

      wx.startBluetoothDevicesDiscovery({
        success: function (res) { },
      })
    }, failCallback)
  }



  /**
   * 打开蓝牙，连接到锁，开始心跳,前提是已经设置过bleLockHelper的chipKey和deviceId
   */
  initBle(successCallback, failCallback) {
    var that = this
    if (this.inConnect) {
      successCallback()
      return
    }
    that.connectStateListener = res => {
      console.log("ble connectState", res)
      if (res.deviceId === bleLockHelper.deviceId) {
        that.inConnect = res.connected
      }
    }
    wx.onBLEConnectionStateChange(that.connectStateListener)

    if (!bleLockHelper.deviceId && bleLockHelper.mac) {

      var name = "TM" + bleLockHelper.mac.replace(/:/g, "")
      this.searchBle(res => {
        var uuid = null

        for (var i = 0; i < res.length; i++) {
          if (res[i].name == name) {
            wx.stopBluetoothDevicesDiscovery()
            uuid = res[i].deviceId
            bleLockHelper.deviceId = uuid
            //ios第一次获取uuid保存
            // lockApi.saveIOSUUID(wx.getStorageSync('housingId'), uuid)
            that._connect(successCallback, failCallback)
            break;
          }
        }
      }, failCallback)
    } else {
      this.openBleAdapter(() => {
        that._connect(successCallback, failCallback)
      }, failCallback)
    }
  }

  _connect(successCallback, failCallback) {
    var that = this
    bleLockHelper.heartFailCallback = res => {
      //心跳失败，回收资源
      wx.showToast({
        title: '蓝牙连接已断开',
        icon: 'none'
      })
      that.releaseBle()
    }
    bleLockHelper.batteryCallback = res => {
      if (res.success && res.data <= 1) {
        wx.showToast({
          title: '门锁电量低',
          icon: 'none'
        })
      }
    }

    bleLockHelper.connect(null, res => {
      that.inConnect = true
      successCallback && successCallback(res)
    }, failCallback)
  }

  stopDiscoveryBLue() {
    var that = this
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) { },
      fail: res => {
        that.stopDiscoveryBLue()
      }
    })
  }

  releaseBle() {
    if (this.inConnect) {
      wx.closeBLEConnection({
        deviceId: bleLockHelper.deviceId,
        fail: err => {
          console.log("关闭连接失败", err)
        }
      })
    }
    if (this.connectStateListener) {
      wx.offBLEConnectionStateChange(this.connectStateListener)
    }
    this.stopDiscoveryBLue()
    if (this.connectStateListener) {
      wx.offBluetoothDeviceFound(this.searchListener)
    }
    if (this.bleAdapterStateListener) {
      wx.offBluetoothAdapterStateChange(this.bleAdapterStateListener)
    }
    bleLockHelper.stopHeart()
    bleLockHelper.clearAllCallback()
    bleLockHelper.session = "00000000"
    // wx.offBLECharacteristicValueChange()//这个在bleLockHelper里，不用关了~
    wx.closeBluetoothAdapter({
      success: function (res) { },
      fail: err => {
        console.log("关闭蓝牙适配器失败", err)
      }
    })
    this.inConnect = false
  }

  /**
   * 从蓝牙设备列表中选出门锁
   */
  _selectDevice(devices) {
    var tempDevice
    console.log("ble", devices[0])
    for (var i = 0; i < devices.length; i++) {
      //ios设备
      if (devices[i].devices != null) {
        if (devices[i].devices.length > 0) {
          tempDevice = devices[i].devices[0];
        } else {
          continue
        }
      } else {
        //安卓
        tempDevice = devices[i];
      }
      console.log("ble", "找到的设备名" + tempDevice.name)
      if (tempDevice && (tempDevice.name.match(/^TM[a-fA-F\d]{12}$/))) {
        if (!this._isExist(tempDevice)) {
          this.bleDevices.push(tempDevice)
        }
        return tempDevice
      }
    }
    return null
  }
  _isExist(device) {
    for (var i = 0; i < this.bleDevices.length; i++) {
      if (this.bleDevices[i].deviceId == device.deviceId) {
        return true
      }
    }
    return false
  }
}
export const bleHelper = new BleHelper()